package com.zivwu.mvp.pick.preview;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.zivwu.mvp.R;
import com.zivwu.mvp.pick.PhotoPicker;
import com.zivwu.utils.model.Photo;

import java.util.ArrayList;
import java.util.List;


public class PhotoPreviewActivity extends AppCompatActivity {
    ViewPager vpPhoto;
    TextView tvIndicator;

    private int currentPageIndex;
    private List<Photo> photoList;
    private RequestOptions requestOptions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mvp_activity_photo_preview);
        vpPhoto = findViewById(R.id.vp_photo);
        tvIndicator = findViewById(R.id.tv_indicator);

        initPrams(getIntent().getExtras());
        initViewPager();
    }

    protected void initPrams(Bundle extras) {
        if (extras == null) {
            return;
        }
        currentPageIndex = extras.getInt(PhotoPicker.EXTRA_PHOTO_INDEX, currentPageIndex);
        photoList = extras.getParcelableArrayList(PhotoPicker.EXTRA_PREVIEW_PHOTO);
        if (photoList != null && photoList.size()==1) {
            tvIndicator.setVisibility(View.GONE);
        }
    }


    private void initViewPager() {
        if (photoList == null) {
            Toast.makeText(this,R.string.mvp_load_fail,Toast.LENGTH_SHORT).show();
            onBackPressed();
        }

        List<View> views = new ArrayList<>();
        for (Photo photo : photoList) {
            views.add(getItem(photo));
        }

        vpPhoto.setAdapter(new ImageAdapter(views));
        vpPhoto.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                CharSequence text = getString(R.string.mvp_viewpager_indicator, position + 1, vpPhoto.getAdapter().getCount());
                setIndicator(text);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        CharSequence text = getString(R.string.mvp_viewpager_indicator, currentPageIndex + 1, vpPhoto.getAdapter().getCount());
        setIndicator(text);
        vpPhoto.setCurrentItem(currentPageIndex);
    }

    private void setIndicator(CharSequence text) {
        tvIndicator.setText(text);
    }

    private SubsamplingScaleImageView getItem(Photo photo) {
        final SubsamplingScaleImageView view = (SubsamplingScaleImageView) LayoutInflater.from(this)
                .inflate(R.layout.mvp_item_photo_preview, vpPhoto, false);

        String data = photo.getData();
        if (data.startsWith("http")) {
            Glide.with(vpPhoto.getContext())
                    .asBitmap()
                    .load(data)
                    .apply(getImageRequestOptions())
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            view.setImage(ImageSource.bitmap(resource));
                        }
                    });
        } else {
            view.setImage(ImageSource.uri(data));
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        return view;
    }


    @SuppressLint("CheckResult")
    private RequestOptions getImageRequestOptions() {
        if (requestOptions != null)
            return requestOptions;
        requestOptions = new RequestOptions();
        requestOptions
                .fitCenter();
        return requestOptions;
    }


    private class ImageAdapter extends PagerAdapter {
        private List<View> photos;

        private ImageAdapter(List<View> photos) {
            this.photos = photos;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(photos.get(position));
            return photos.get(position);
        }


        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(photos.get(position));
        }

        @Override
        public int getCount() {
            return photoList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }
}
